package com.biodiv.community.config;

import com.biodiv.community.base.ResponseEntity;
import com.biodiv.community.enums.ErrorEnum;
import com.biodiv.community.exception.CommunityException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;

/**
 * @author tianquan
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     */
    @ExceptionHandler(CommunityException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleBusinessException(CommunityException ex) {
        logger.error("业务异常: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ResponseEntity.error(ex.getCode(), ex.getMessage()));
    }

    /**
     * 处理授权异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleAccessDeniedException(AccessDeniedException ex) {
        logger.error("权限不足: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(ResponseEntity.error(ErrorEnum.FORBIDDEN.getCode(), ex.getMessage()));
    }

    /**
     * 处理请求参数绑定异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        bindingResult.getFieldErrors().forEach(fieldError ->
                errorMsg.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("; ")
        );

        logger.error("参数验证失败: {}", errorMsg.toString());
        return org.springframework.http.ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ResponseEntity.error(ErrorEnum.VALIDATION_ERROR.getCode(), errorMsg.toString()));
    }

    /**
     * 处理请求参数类型不匹配异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        logger.error("请求参数格式错误: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(ResponseEntity.error(ErrorEnum.INVALID_PARAMETER.getCode(), "请求参数格式错误"));
    }

    /**
     * 处理请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        logger.error("不支持的请求方法: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED)
                .body(ResponseEntity.error(ErrorEnum.METHOD_NOT_ALLOWED.getCode(), ex.getMessage()));
    }


    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleNullPointerException(NullPointerException ex) {
        logger.error("空指针异常: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ResponseEntity.error(ErrorEnum.INTERNAL_SERVER_ERROR.getCode(), "服务器内部错误"));
    }

    /**
     * 处理其他所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public org.springframework.http.ResponseEntity<ResponseEntity> handleGlobalException(Exception ex) {
        logger.error("系统异常: {}", ex.getMessage(), ex);
        return org.springframework.http.ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ResponseEntity.error(ErrorEnum.INTERNAL_SERVER_ERROR.getCode(), "服务器内部错误，请稍后重试"));
    }
}
